<!-- 登录注册弹框 -->
<template>
  <div class="loginDailog">
    <van-popup v-model:show="authStore.isLoginDialogVisible" class="custom-popup" @close="handleClose">
      <!-- 顶部 -->
      <div class="top">
        <img src="@/assets/images/ic_close@2x.png" alt="" @click="handleClose" />
      </div>
      <!-- 登录弹窗 -->
      <div class="login_wrap" v-if="authStore.isLogin">
        <div class="title">Login</div>
        <div class="select_way" @click="loginGoogle">
          <img src="@/assets/images/logo_google@2x.png" alt="" />
          <span class="text">Log in with Google</span>
        </div>
        <van-form @submit="loginSubmit">
          <van-cell-group inset>
            <van-field v-model="loginForm.username" name="username" label="" placeholder="Email"
              :rules="[{ required: true, message: 'Please enter your email' }]" />
            <van-field v-model="loginForm.password" :type="showPassword ? 'text' : 'password'" name="password" label=""
              placeholder="Password" :rules="[{ required: true, message: 'Please enter your password' }]">
              <template #right-icon>
                <img src="@/assets/images/icon_eye_2@2x.png" alt="" class="password_img" v-if="!showPassword"
                  @click="changeBtnStatus" />
                <img src="@/assets/images/icon_eye_1@2x.png" alt="" class="password_img" v-else
                  @click="changeBtnStatus" />
              </template>
            </van-field>
          </van-cell-group>
          <div style="margin: 0px">
            <van-button round block type="primary" native-type="submit"> Login </van-button>
          </div>
        </van-form>
        <div class="bottom_tips">
          <p class="fisrt_tips">
            <span>Don't have an account yet?</span>
            <span class="word_click" @click="goSignIn">Sign in</span>
          </p>
          <p class="second_tips" @click="resetPassWord">Forgot your password?</p>
        </div>
      </div>
      <!-- 注册弹框 -->
      <div class="signin_wrap" v-else>
        <div class="title">Sign in</div>
        <div class="select_way select_way_second" @click="loginGoogle">
          <img src="@/assets/images/logo_google@2x.png" alt="" />
          <span class="text">Continue with Google</span>
        </div>
        <van-divider>OR</van-divider>
        <p class="top_select_tips"></p>
        <van-form @submit="register">
          <van-cell-group inset>
            <van-field v-model="signInForm.username" name="username" label="" placeholder="Email"
              :rules="[{ required: true, message: 'Please enter your email' }]" />
            <van-field v-model="signInForm.password" type="password" name="password" label="" placeholder="Password"
              :rules="[{ required: true, message: 'Please enter your password' }]">
            </van-field>
          </van-cell-group>
          <div style="margin: 0px">
            <van-button round block type="primary" native-type="submit">
              Create an account
            </van-button>
          </div>
        </van-form>
        <div class="bottom_tips">
          <p class="fisrt_tips">
            <span>Don't have an account yet?</span>
            <span class="word_click" @click="goLogin">log in</span>
          </p>
          <p class="second_tips_text">By registering, you agree to our</p>
          <p class="second_tips">Privacy Policy & Terms of Service</p>
        </div>
      </div>
    </van-popup>
    <!-- 重置密码 -->
    <van-popup v-model:show="isResetPassword" class="custom-popup custom-popup-reaset" @close="handleCloseReset">
      <div v-if="isSecondStep">
        <!-- 顶部 -->
        <div class="top">
          <van-icon name="cross" @click="handleCloseReset" />
        </div>
        <div class="title">Retrieve password</div>
        <p class="tips_word">Enter your email address and we will send you a password</p>
        <van-form @submit="continueBtn">
          <van-cell-group inset>
            <van-field v-model="username" name="username" label="" placeholder="Email"
              :rules="[{ required: true, message: 'Please enter your email address' }]" />
          </van-cell-group>
          <div style="margin-top: 6px">
            <van-button round block type="primary" native-type="submit" @click="continueShowDialog">
              Continue
            </van-button>
          </div>
        </van-form>
      </div>
      <div v-else class="change_password">
        <div class="top">
          <van-icon name="cross" @click="closeSecondPop" />
        </div>
        <div class="title">Change password</div>
        <van-form @submit="saveChangeBtn">
          <van-cell-group inset>
            <p class="tips_word tips_word_last">Current Password</p>
            <van-field v-model="username" name="username" label="" placeholder="Enter your current password"
              :rules="[{ required: true, message: 'Password error' }]" />
            <p class="tips_word tips_word_last">New Password</p>
            <van-field v-model="username" name="username" label="" placeholder="New Password" :rules="[
              {
                required: true,
                message:
                  'Password Password requirements: more than 6 characters, must have letters and numbers',
              },
            ]" />
            <p class="tips_word tips_word_last">Confirm New Password</p>
            <van-field v-model="username" name="username" label="" placeholder="Confirm new password"
              :rules="[{ required: true, message: 'The second password is inconsistent' }]" />
          </van-cell-group>
          <div style="margin: 0px">
            <van-button round block type="primary" native-type="submit" @click="showDialogEvent">
              Save changes
            </van-button>
          </div>
        </van-form>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { showConfirmDialog, showDialog, showFailToast, showToast } from "vant";
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { useAuthStore } from "@/stores/authStore";
import api from "@/api";
import { trackEvent } from "@/utils/firebase";

const router = useRouter();
const authStore = useAuthStore();

// 暴露方法给父组件（如果需要手动控制）
defineExpose({
  closeDialog: () => {
    authStore.hideLoginDialog();
  },
});

// 谷歌登录
const loginGoogle = async () => {
  try {
    const res = await api.googleAuthUrl();
    if (res.code === 200 && res.data.authUrl) {
      window.location.href = res.data.authUrl;
    }
  } catch (error) {
    console.error("获取google授权url 失败:", error);
    throw error;
  }
};

// 登录
const loginForm = reactive({
  deviceId: localStorage.getItem("baseFingerprint"),
  password: "",
  username: "",
});
const showPassword = ref(false);

// safety code 按钮状态
const changeBtnStatus = () => {
  showPassword.value = !showPassword.value;
};

// 注册
const signInForm = reactive({
  deviceId: localStorage.getItem("baseFingerprint"),
  password: "",
  username: "",
});

// 是登录还是注册
const goSignIn = () => {
  authStore.isLogin = false;
  trackEvent("展示_注册弹窗", { id: "100062" }); //埋点
};
const goLogin = () => {
  authStore.isLogin = true;
  trackEvent("展示_登录弹窗", { id: "100061" }); //埋点
};

// 关闭
const handleClose = () => {
  authStore.hideLoginDialog(); // 关闭登录弹窗
};
// 登录注册弹框
const username = ref("");

// 用户登录
const loginSubmit = async () => {

  try {
    loginForm.deviceId = localStorage.getItem("baseFingerprint");
    await authStore.login(loginForm, router);
    authStore.hideLoginDialog(); // 关闭登录弹窗
    showToast('Login succeeded');
    trackEvent("登录成功", { id: "100063", type: "2" }); //埋点
  } catch (error) {
    showFailToast(error.message);
  }
};

// 用户注册
const register = async () => {
  try {
    signInForm.deviceId = localStorage.getItem("baseFingerprint");
    await authStore.login(signInForm, router);
    authStore.hideLoginDialog(); // 关闭登录弹窗
    showToast('Login succeeded');
    trackEvent("登录成功", { id: "100063", type: "4" }); //埋点
  } catch (error) {
    showFailToast(error.message);
  }
};

//重置密码
const isResetPassword = ref(false);
const resetPassWord = () => {
  isResetPassword.value = true;
};
const handleCloseReset = () => {
  isResetPassword.value = false;
};

const isSecondStep = ref(true);
const closeSecondPop = () => {
  isSecondStep.value = false;
};
const continueBtn = () => { };
const continueShowDialog = () => {
  showDialog({
    message: "The password has been sent to your email, please check",
    className: "custom-login-dialog",
    confirmButtonText: "OK",
  }).then(() => {
    // on close
  });
};
const saveChangeBtn = () => { };
const showDialogEvent = () => {
  showConfirmDialog({
    title: "",
    confirmButtonText: "OK",
    cancelButtonText: "Cancel",
    message: "The password has been changed. Please keep it safe",
  })
    .then(() => {
      // on confirm
      isSecondStep.value = true;
      isResetPassword.value = false;
      handleClose();
    })
    .catch(() => {
      // on cancel
    });
};

onMounted(() => {
  trackEvent("展示_登录弹窗", { id: "100061" }); //埋点
});
</script>

<style scoped lang="less">
.loginDailog {
  :deep(.custom-popup) {
    width: 328px;
    min-height: 507px;
    padding: 8px 24px 28px 24px;
    box-sizing: border-box;
    background: #ffffff;
    box-shadow: 0px 12px 16px 0px rgba(0, 0, 0, 0.15);
    border-radius: 8px;

    .top {
      display: flex;
      justify-content: right;
      align-items: center;

      img {
        width: 24px;
        margin-right: -16px;
      }
    }

    .van-form {
      .van-cell-group {
        background: none;
        padding: 0;
      }

      .van-cell-group--inset {
        border-radius: 0;
        margin: 0;
      }

      .van-cell {
        margin-bottom: 24px;
        padding: 0;
        background: none;

        .van-field__control {
          width: 100%;
          height: 56px;
          box-sizing: border-box;
          border: 1px solid rgba(0, 0, 0, 0.45);
          background-color: #fff;
          border-radius: 8px;
          font-size: 15px;
          color: rgba(0, 0, 0, 0.45);
          text-align: left;
          box-sizing: border-box;
          padding: 19px 24px;
        }

        .van-field__error-message {
          font-size: 13px;
          color: #d9001b;
          box-sizing: border-box;
          padding: 0 10px;
        }
      }

      .van-cell:after {
        display: none;
      }

      .van-button {
        width: 100%;
        height: 64px;
        margin: 0 auto;
        background-color: #89a5ff;
        box-sizing: border-box;
        border: 0;
        border-radius: 4px;
        font-weight: 700;
        background: linear-gradient(90deg, #89a5ff 0%, #6b77ff 100%);
        font-size: 20px;
        color: #ffffff;
      }

      .password_img {
        width: 28px;
        position: absolute;
        right: 33px;
        top: 14px;
      }
    }

    .signin_wrap,
    .login_wrap {
      .van-field__right-icon {
        padding: 0;
        margin: 0;
      }

      .send_password_btn {
        width: 76px;
        height: 40px;
        line-height: 40px;
        background: linear-gradient(90deg, #ffd52f 0%, #f874ff 50%, #516eff 100%);
        border-radius: 4px;
        font-size: 13px;
        color: #ffffff;
        text-align: center;
        position: absolute;
        right: 9px;
        top: 9px;
      }

      .title {
        font-size: 24px;
        color: rgba(0, 0, 0, 0.95);
        font-weight: 700;
        text-align: center;
      }

      .select_way {
        width: 280px;
        height: 56px;
        background: #ffffff;
        border-radius: 8px;
        border: 1px solid rgba(0, 0, 0, 0.1);
        display: flex;
        justify-content: center;
        align-items: center;
        margin-top: 32px;
        margin-bottom: 24px;

        img {
          width: 24px;
        }

        .text {
          font-size: 15px;
          color: rgba(0, 0, 0, 0.95);
          margin-left: 4px;
        }
      }

      .select_way_second {
        margin-bottom: 15px;
      }

      .bottom_tips {
        text-align: center;

        .fisrt_tips {
          font-size: 15px;
          color: rgba(0, 0, 0, 0.95);
          margin-top: 24px;

          .word_click {
            color: #6251ff;
            font-weight: 600;
            margin-left: 5px;
          }
        }

        .second_tips {
          text-decoration: underline;
          font-size: 13px;
          color: rgba(0, 0, 0, 0.45);
        }
      }
    }

    .signin_wrap {
      .top_select_tips {
        text-align: center;
        margin-bottom: 17px;
      }

      .second_tips_text {
        margin-top: 14px;
        font-size: 13px;
        color: rgba(0, 0, 0, 0.45);
      }

      .van-divider {
        margin: 0 12px;
      }
    }
  }

  :deep(.custom-popup-reaset) {
    min-height: 264px;

    .top {
      text-align: right;
      box-sizing: border-box;
      padding: 10px;

      .van-icon {
        font-size: 18px;
        color: #000;
        font-weight: 700;
      }
    }

    .title {
      text-align: center;
      font-size: 24px;
      color: rgba(0, 0, 0, 0.95);
      font-weight: 700;
    }

    .tips_word {
      width: 253px;
      margin: 0 auto;
      margin-top: 15px;
      text-align: left;
      margin-bottom: 24px;
      font-size: 17px;
      color: rgba(0, 0, 0, 0.95);
    }

    .tips_word_last {
      margin-top: 0;
      margin-bottom: 4px;
    }

    .change_password {
      .title {
        margin-bottom: 16px;
      }

      .van-form .van-cell {
        margin-bottom: 12px;
      }
    }
  }
}
</style>
